/*
 * @Author: wuqingchun
 * @Date: 2025-01-21 10:33:00
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2025-01-21 17:59:07
 */

#include <stdio.h>

#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>

#include "rpc_msg.h"
#include "rpc_client.h"


int32_t RPCClient::Init(const char* pcURL)
{
    m_iNNSock = nn_socket(AF_SP, NN_REQ);
    if (m_iNNSock == -1)
    {
        return -1;
    }

    int32_t iErr = nn_connect(m_iNNSock, pcURL);
    if (iErr == -1)
    {
        nn_close(m_iNNSock);
        m_iNNSock = -1;
    }

    return iErr;
}

int32_t RPCClient::Call(int32_t iFuncID, int32_t iArg1, int32_t iArg2)
{
    if (m_iNNSock == -1)
    {
        return -1;
    }
    
    RpcRequest stMsg{};

    stMsg.iFuncID = iFuncID;
    stMsg.iArg1 = iArg1;
    stMsg.iArg2 = iArg2;

    return nn_send(m_iNNSock, &stMsg, sizeof(stMsg), 0);
}


int32_t RPCClient::Recv()
{
    if (m_iNNSock == -1)
    {
        return -1;
    }

    RpcReply stReply{};
    int32_t iErr = nn_recv(m_iNNSock, &stReply, sizeof(stReply), 0);
    if (iErr == -1)
    {
        return iErr;
    }

    if (stReply.iErr == -1)
    {
        printf("Function %d is unsupported\n", stReply.iFuncID);
    }
    else
    {
        printf("Call %d Result: %d\n", stReply.iFuncID, stReply.iResult);
    }

    return 0;
}

void RPCClient::OnMessage()
{
}